<?php

namespace App\Http\Requests\Api;

use App\Http\Requests\Request;
use App\Models\Api\ApiResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\JsonResponse;

class ApiRequest extends Request
{
    //
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    //重写返回的错误信息
    protected function formatErrors(Validator $validator)
    {
        if ($this->wantsJson()) {//通过判断head中accept是否有json字段
            return ApiResponse::fail($validator->errors()->first());
        }
        return parent::formatErrors($validator); // TODO: Change the autogenerated stub
    }

    //重写返回的错误statusCode
    public function response(array $errors)
    {
        if (($this->ajax() && ! $this->pjax()) || $this->wantsJson()) {
            return new JsonResponse($errors, 200);
        }
        return parent::response($errors);
    }

    /** 过滤参数
     * @param array|mixed $keys 需要保留的key,如果参数里没有key,也不保留
     * key所对应的value为空时,也保留,如果value为空时,也不想保留则用request->intersect()
     * @return array
     */
    public function strictOnly($keys) {
        $keys=is_array($keys) ? $keys : func_get_args();
        //当前request的keys和参数keys交集
        $only_keys=array_intersect($keys, array_keys($this->all()));

        return $this->only($only_keys);
    }

    public function messages()
    {
        return [
            'required' => ':attribute不能为空',
            'required_if' => ':attribute不能为空',
            'required_with' => ':attribute不能为空',
            'integer'=>':attribute必需是整数',
            'min'=>':attribute不能小于:min',
            'max'=>':attribute不能大于:max',
            'email'=>'邮箱格式不对',
            'numeric'=>':attribute必需是数字',
            'image'=>':attribute必需是图片',
            'mimes'=>':attribute图片格式只能是:jpg,bmp,png',
            'array'=>':attribute必需是数组',
            'between'=>':attribute必需在:min~:max之间',
            'date' => ':attribute时间格式不正确',
            'mobile.mobile_verification'=>'请输入正确的手机号码',
            'phone.check_company_phone'=>'请输入正确的区号和电话号码',
            'api_check_username'=>':attribute格式不正确'
        ];
    }
}
